/**   
 *    
 * 项目名称：SmartKungFuService   
 * 类名称：ClientCourseServlet   
 * 类描述：   我的课程接口
 * 创建人：zhanghl  
 * 创建时间：2016年9月28日 上午10:44:41   
 * 修改人：zhanghl   
 * 修改时间：2016年9月28日 上午10:44:41   
 * 修改备注：   
 * @version    
 *    
 */
package com.lst.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.lst.base.entity.BaseRequest;
import com.lst.base.entity.BaseResponse;
import com.lst.common.CommCode;
import com.lst.entity.request.ClientCourseReqPara;
import com.lst.entity.response.ClientCourseResPara;
import com.lst.model.ClientCourse;
import com.lst.model.MstOrder;
import com.lst.model.OrderDetail;
import com.lst.service.ClientCourseService;
import com.lst.service.MstOrderService;
import com.lst.service.OrderDetailService;
import com.lst.utils.DateUtil;
import com.lst.utils.RequestUtils;

/**
 * @ClassName: ClientCourseServlet
 * @Description: 我的课程接口
 * @author zhanghl
 * @date 2016年9月28日 上午10:44:41
 *
 */
public class ClientCourseServlet extends BaseServlet {

	private static final long serialVersionUID=1L;

	private ClientCourseService clientCourseService = ctx.getBean(ClientCourseService.class);
	
	private MstOrderService mstOrderService = ctx.getBean(MstOrderService.class);

	private OrderDetailService orderDetailService = ctx.getBean(OrderDetailService.class);

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request,response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		ClientCourseResPara resPara = new ClientCourseResPara();

		try{
			ClientCourseReqPara reqPara=getReqPara(request);

			if(isCheckField(reqPara,resPara)){
				Integer clientid = Integer.valueOf(reqPara.getUserid());	
				Integer page = Integer.valueOf(reqPara.getPage());
				Integer pagesize = Integer.valueOf(reqPara.getPagesize());

				Map<String, Object> ccMap = new HashMap<String, Object>();

				ccMap.put("enabled", true);
				ccMap.put("isDeleted", false);
				ccMap.put("clientid", clientid);
				ccMap.put("acttype", CommCode.SYSTEM_CARESEL_RANGE_COURSE);
				ccMap.put("orderByClause", "o.updatedate desc");

				PageBounds pageBounds = new PageBounds(page , pagesize);

				List<ClientCourse> list = clientCourseService.queryList(ccMap, pageBounds);

				PageBounds pagebounds = new PageBounds();

				if (list.isEmpty()){
					resPara.setCourselist(list);
					resPara.setCode(CommCode.M_Y000000);
					resPara.setMessage(CommCode.M_Y000001);
				} else {
					List<ClientCourse> cclist = new ArrayList<ClientCourse>();

					for(ClientCourse cc:list){

						ccMap.put("orderid", cc.getO().getId());

						List<ClientCourse> clilist = clientCourseService.queryByList(ccMap,pagebounds);
						
						//获取已经报名数量
						Map<String, Object> momap = new HashMap<String, Object>();

						momap.put("enabled", true);
						momap.put("isDeleted", false);				
						momap.put("acttype", CommCode.SYSTEM_CARESEL_RANGE_COURSE);
						momap.put("actid", clilist.get(0).getGd().getId());	

						List<MstOrder> moList =  mstOrderService.queryByList(momap, pagebounds);

						Integer countnum = 0;

						for(MstOrder m : moList){

							momap.clear();
							momap.put("enabled", true);
							momap.put("isDeleted", false);
							momap.put("orderid", m.getId());	

							List<OrderDetail> odlist = orderDetailService.queryByList(momap, pagebounds);

							if(CommCode.SYSTEM_ORDER_STATUS_WAIT.equals(odlist.get(0).getOrderstatus())){
								countnum += m.getNum() == null ? 0 : m.getNum();
							}
						}

						Integer leavenum = clilist.get(0).getGd().getLimitnum() - countnum;

						if(leavenum>=0){
							clilist.get(0).getGd().setLeavenum(leavenum);
						}else{
							clilist.get(0).getGd().setLeavenum(0);
						}

						if(!clilist.isEmpty()){

							//隐藏手机号
							if(!StringUtils.isEmpty(clilist.get(0).getO().getPhoneno())){
								String clientphonone = clilist.get(0).getO().getPhoneno().replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2");
								clilist.get(0).getO().setClientphonone(clientphonone);		
							}	

							//倒计时
							if(!StringUtils.isEmpty(clilist.get(0).getO().getScheid())){							

								Date start = DateUtil.parse(clilist.get(0).getO().getScheid());										

								Date date = new Date();

								Date startdate = DateUtil.getFormatDate(start,DateUtil.ALL_DATE_HORIZONTAL);

								Date  currentDate = DateUtil.getFormatDate(date, DateUtil.ALL_DATE_HORIZONTAL);

								int countdown = (int)((startdate.getTime()-currentDate.getTime())/86400000);

								if(countdown>0){
									clilist.get(0).getGd().setCountdown(countdown);
								}else {
									clilist.get(0).getGd().setCountdown(0);
								}
							}							
							cclist.add(clilist.get(0));
						}						

					}	
					resPara.setCourselist(cclist);
					resPara.setCode(CommCode.M_Y000000);
					resPara.setMessage(CommCode.M_Y000001);
				} 					

			}

		} catch(Exception e){

			resPara.setCode(CommCode.M_A000000);
			resPara.setMessage(CommCode.M_SYS0001);

			logger.error("doPost error: ", e);
		}

		try {
			response.setContentType("application/json;charset=utf-8");
			response.setHeader("pragma", "no-cache");
			response.setHeader("cache-control", "no-cache");

			Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").excludeFieldsWithoutExposeAnnotation().serializeNulls().create();
			String jsonResult = gson.toJson(resPara);

			logger.info("ClientCourseServlet jsonResult: " + jsonResult);

			PrintWriter out = response.getWriter();
			out.print(jsonResult);
			out.flush();
			out.close();

		} catch (Exception e) {
			resPara.setCode(CommCode.M_A000000);
			resPara.setMessage(CommCode.M_SYS0003);

			logger.error("doPost error: ", e);
		}
	}

	@Override
	public ClientCourseReqPara getReqPara(HttpServletRequest request) {

		ClientCourseReqPara reqPara =null;
		try{
			BaseRequest baseRequest = RequestUtils.getRequestPara(request, new ClientCourseReqPara());
			reqPara = (ClientCourseReqPara)baseRequest.clone();

			String userid = request.getParameter("userid");
			String page = request.getParameter("page");
			String pagesize = request.getParameter("pagesize");

			reqPara.setUserid(userid);
			reqPara.setPage(page);
			reqPara.setPagesize(pagesize);

		}catch(Exception e){
			logger.info("getReqPara error: ",e);
		}
		return reqPara;
	}

	@Override
	public boolean isCheckField(BaseRequest reqPara, BaseResponse resPara) {
		boolean flag = false;

		ClientCourseReqPara ccReqPara = (ClientCourseReqPara) reqPara;
		ClientCourseResPara ccResPara = (ClientCourseResPara) resPara;

		if(StringUtils.isEmpty(ccReqPara.getUserid())){
			ccResPara.setCode(CommCode.M_A000000);
			ccResPara.setMessage(CommCode.M_P000002);
		} else if (StringUtils.isEmpty(ccReqPara.getPage())){
			ccResPara.setCode(CommCode.M_A000000);
			ccResPara.setMessage(CommCode.M_P000009);
		} else if (StringUtils.isEmpty(ccReqPara.getPagesize())){
			ccResPara.setCode(CommCode.M_A000000);
			ccResPara.setMessage(CommCode.M_P000010);
		} else {
			flag = true;
		}		
		return flag;
	}
}
